<template>
  <div class="app-container">
    <el-input v-model="filterText" placeholder="Filter keyword" style="margin-bottom:30px;"/>

    <!-- 工具条 -->
    <div>
      <el-button type="primary" size="mini" @click="addMenu(form.parentId)" v-if="hasPerm('system:menu:add')">添加</el-button>
    </div>

    <el-table
      :data="menuList"
      row-key="id"
      border
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        
      <el-table-column
        prop="menuName"
        label="菜单名称"
        align="center"
        sortable
        width="120">
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        align="center"
        sortable
        width="100">
      </el-table-column>
      <el-table-column
        prop="path"
        label="访问路径"
        align="center"
        sortable
        width="240">
        <template slot-scope="scope">
          {{ (scope.row.path === null || scope.row.path === '') ? '#' : scope.row.path}}
        </template>
      </el-table-column>
      <el-table-column
        prop="component"
        label="组件路径"
        align="center"
        sortable
        width="240">
        <template slot-scope="scope">
          {{ (scope.row.component === null || scope.row.component === '') ? '#' : scope.row.component}}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="80" prop="menuType">
        <template slot-scope="scope">
          {{ scope.row.menuType===1 ? '目录':(scope.row.menuType ===2 ? '菜单':'按钮') }}
        </template>
      </el-table-column>
      <el-table-column
        prop="perms"
        label="权限标识"
        align="center"
        width="180">
        <template slot-scope="scope">
          {{ (scope.row.perms === null || scope.row.perms === '') ? '-' : scope.row.perms}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="hasPerm('system:menu:add')"
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="addMenu(scope.row.id)">添加
          </el-button>
          <el-button
            v-if="hasPerm('system:menu:update')"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="updateMenu(scope.row.id)">编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeById(scope.row.id)" v-if="hasPerm('system:menu:remove')">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="title">
      <el-form ref="form" :model="form" :rules="validateRules" label-width="120px">
        <el-form-item v-if="form.menuType != '1'" label="上级菜单" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="menuOptions"
            
            :show-count="true"
            placeholder="选择上级菜单"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="form.menuType">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>  
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName"/>
        </el-form-item>
        <el-form-item v-if="form.menuType != '3'" label="菜单图标" prop="menuIcon">
          <!-- <el-input v-model="form.menuIcon"/> -->
          <el-popover
            placement="bottom-start"
            width="460"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selected" />
            <el-input slot="reference" v-model="form.menuIcon" placeholder="点击选择图标" readonly>
              <svg-icon
                v-if="form.menuIcon"
                slot="prefix"
                :icon-class="form.menuIcon"
                class="el-input__icon"
                style="height: 32px;width: 16px;"
              />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item v-if="form.menuType != '3'" label="访问路径" prop="path">
          <el-input v-model="form.path"/>
        </el-form-item>
        <el-form-item v-if="form.menuType == '2'" label="组件路径" prop="component">
          <el-input v-model="form.component"/>
        </el-form-item>
        <el-form-item v-if="form.menuType != '1'" label="权限标识" prop="perms">
          <el-input v-model="form.perms"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort"/>
        </el-form-item>
        
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :label='1'>启用</el-radio>
            <el-radio :label='0'>停用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="handleClose()">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import menuApi from '@/api/system/menu'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";

const menuForm = {
  perms: '',
  menuName: '',
  parentId: 0,
  path: '',
  component: '',
  menuType: 0,
  menuIcon: '',
  sort: 0,
  state: 1
}

export default {
  name: "Menu",
  components: { Treeselect, IconSelect },
  data() {
    return {
      filterText: '',
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      title: '添加菜单',
      dialogVisible: false,
      form: menuForm,
      validateRules: {
        menuName: [{required: true, trigger: 'blur', message: '菜单名称不能为空'}],
        path: [{required: true, trigger: 'blur', message: '菜单路径不能为空'}],
        component: [{required: true, trigger: 'blur', message: '组件名称不能为空'}],
        sort: [{required: true, trigger: 'blur', message: '排序不能为空'}],
        state: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      },
      menuOptions: [],
      saveBtn: false,
      editMenuType: 0
    }
  },
  // 监听上面文本框搜索
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },

  created() {
    this.fetchNodeList()
  },

  methods: {
    // 选择图标
    selected(name) {
      console.log(name)
      this.form.menuIcon = name;
    },
    fetchNodeList() {
      menuApi.tree().then(response => {
        if (response.code === 200) {
          this.menuList = response.data
        }
      })
    },
    // filterNode(value, data) {
    //   if (!value) return true
    //   return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1
    // },
    
    getById(data) {
      this.dialogVisible = true
      this.menu = data
    },
    saveData(form){
      menuApi.addMenu(form).then(response =>{
        if(response.code ===200) {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.dialogVisible = false;
          this.saveBtn = false
          this.fetchNodeList();
        }
      });
    },
    updateData(form){
      menuApi.updateMenu(form).then(response =>{
        if(response.code ===200) {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.dialogVisible = false;
          this.saveBtn = false
          this.fetchNodeList();
        }
      });
    },
    // 确认
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveBtn = true
          let form = this.form
          if(form.parentId == undefined) {
            this.form.parentId = 0
          }
          
          // 修改
          if (form.id != undefined) {
            if(form.menuType ===1){
              this.$message({
                type: 'warning',
                message: '主菜单不能选择'
              })
              return
            }

            if(form.menuType != this.editMenuType){
              this.$message({
                type: 'warning',
                message: '请确认菜单类型是否一致'
              })
              return
            }

            this.updateData(form)
          } else {// 新增
            this.saveData(form)
          }
        }
      })
    },
    // 取消
    handleClose() {
      this.dialogVisible = false
      this.form = {...menuForm}
    },
    // 表单重置
    reset() {
      this.form = {};
    },
    // 新增
    addMenu(id){
      this.reset()
      this.dialogVisible = true
      this.title = "修改菜单";
      if(id != 0) {
        this.form.parentId = id
      }
      
      menuApi.menuTree().then(response => {
        if (response.code === 200) {
          this.menuOptions = response.data
        }
      })
    },
    // 修改
    updateMenu(id){
      this.reset();
      this.dialogVisible = true
      menuApi.getMenuById(id).then(response => {
        this.form = response.data;
        this.editMenuType = this.form.menuType
        if(this.form.menuType === 1) {
          this.form.parentId = null
        }
        this.open = true;
        this.title = "修改菜单";
      });

      menuApi.menuTree().then(response => {
        if (response.code === 200) {
          this.menuOptions = response.data
        }
      })
    },
    removeById(id){
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return menuApi.removeById(id)
      }).then((response) => {
        this.fetchData(this.page)
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch((error) => {
        this.$message({
          type: 'warning',
          message: error.message === undefined ? '已取消删除':error.message
        })
      })
    }
  }
}
</script>
